<?php
/**
 * 消费系统的余额语音预警
 */
namespace frontend\modules\business\controllers;

use yii;
use yii\web\Controller;
use yii\helpers\Url;
use yii\helpers\Json;

class WarningController extends Controller
{
    
    public $consume = null;
    
    public function init()
    {
        parent::init();
        
        $this->enableCsrfValidation = false;

        $masterConfig = $this->module->params['consume'];
        
        $this->consume = new yii\db\Connection([
            'dsn' => "mysql:host={$masterConfig['host']};dbname={$masterConfig['dbname']}",
            'username' => $masterConfig['username'],
            'password' => $masterConfig['password'],
            'charset' => $masterConfig['charset'],
            'tablePrefix' => $masterConfig['tablePrefix'],
        ]);
        
    }

    public function actionIndex()
    {
        return Json::encode(['msg'=>'thank you!']);
    }
    
    public function actionBalanceVolice()
    {
        $allow_sms_scene = [
            'warningBalance',
            'warningVolice'
        ];
        
        $data = Yii::$app->request->get('date');
        
        $sms_scene = Yii::$app->request->get('sms_scene');
        
        if ($sms_scene && !in_array($sms_scene, $allow_sms_scene)) {
            return Json::encode(['msg'=>'bye!']);
        }
        
        if ($data) {
            $input_time = strtotime($data);
            $begin_time = strtotime(date('Y-m-d 00:00:00', $input_time));
            $end_time = strtotime(date('Y-m-d 23:59:59', $input_time));
        } else {
            $begin_time = strtotime(date('Y-m-d 00:00:00'));
            $end_time = strtotime(date('Y-m-d 23:59:59'));
        }

        $where = ['between', 'createtime', $begin_time, $end_time] ;
        
        if ($sms_scene) {
            $where['sms_scene'] = [$sms_scene];
        } else {
            $where['or'] = ["sms_scene='warningBalance'", "sms_scene = 'warningVolice'"];
        }

        $list = (new \yii\db\Query())
        ->from('consume_sms_record')
        ->where($where)
        ->orderBy('admin_id asc, createtime asc')
        ->all($this->consume);


        return $this->render('balanceVolice',['list'=>$list]);
    }

}
